package com.npy.reggie.contorller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.npy.reggie.config.BaseConText;
import com.npy.reggie.doman.R;
import com.npy.reggie.doman.ShoppingCart;
import com.npy.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;


    @GetMapping("/list")
    public R<List<ShoppingCart>>  listR(){

        QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<>();

        queryWrapper.lambda().eq(BaseConText.getCurrentId()!=null,ShoppingCart::getUserId,BaseConText.getCurrentId());

        return R.success(shoppingCartService.list(queryWrapper));

    }

    @PostMapping("/add")
    public R<ShoppingCart> addShoppingCart(@RequestBody ShoppingCart shoppingCart){

        shoppingCart.setUserId(BaseConText.getCurrentId());

        shoppingCart.setCreateTime(LocalDateTime.now());

        QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<>();

        queryWrapper.lambda().eq(shoppingCart
                .getSetmealId()!=null,
                ShoppingCart::getSetmealId,
                shoppingCart.getSetmealId());

        queryWrapper.lambda().eq(shoppingCart
                        .getDishId()!=null,
                ShoppingCart::getDishId,
                shoppingCart.getDishId());

        queryWrapper.lambda().eq(BaseConText.getCurrentId()!=null,ShoppingCart::getUserId,BaseConText.getCurrentId());

        ShoppingCart one = shoppingCartService.getOne(queryWrapper);
        if (one==null){
            shoppingCart.setNumber(1);
            shoppingCartService.save(shoppingCart);
            one= shoppingCart;
        }else {
            one.setNumber(one.getNumber()+1);
            shoppingCartService.updateById(one);
        }
       return R.success(one);
    }
}
